<template>
    <div>
        <div class="tabs-nav-bar scale-1px">
            <div class="tab-item-wrap" @click="fetchOrderDataByStatus(orderStatusItem)" v-for="(orderStatusItem, index) in orderStatus" :key="index">
                <div class="tab-item" :class='[orderStatusItem.status === curStatus ? "active": ""]'>
                    {{orderStatusItem.name}}
                </div>
            </div>
        </div>
        <div class="order-container">
            <div class="order-status-container">
                <div class="order-item-container" v-for="(orderItem, index) in orderList" :key="index">
                    <productListItem v-for="(productItem, index) in orderItem.products" :key="index" :productItem="productItem"> 
                    </productListItem>
                    <div class="order-item-footer" v-if="orderItem.status==='UNPAY'">
                        <span class="cancel-btn" v-if="computedHasEnd(orderItem.whenCreated)>0">
                            <time-count-down :start-time="computedStartTime(orderItem.whenCreated)" :end-time="computedEndTime(orderItem.whenCreated)"></time-count-down>
                        </span>
                        <span class="cancel-btn" @click="deleteHandler(orderItem)">取消订单</span>
                        <span class="pay-btn" @click="payOrder(orderItem.id)">
                            支付<span class="order-item-transactionprice">¥{{orderItem.transactionPrice}}</span>
                        </span>
                    </div>
                    <div class="order-item-footer" v-if="orderItem.status==='UNRECEIVED'">
                        <span class="cancel-btn" @click="openLogisticModal(orderItem)">订单详情</span><span class="pay-btn order-finished">待收货¥{{orderItem.transactionPrice}}</span>
                    </div>
                    <div class="order-item-footer" v-if="orderItem.status==='CANCELED'">
                        <span class="pay-btn order-finished">已取消</span>
                    </div>
                    <div class="order-item-footer" v-if="orderItem.status==='FINISHED'">
                        <span class="cancel-btn" @click="openLogisticModal(orderItem)">订单详情</span><span class="pay-btn order-finished">已完成¥{{orderItem.transactionPrice}}</span>
                    </div>
                </div>
                <div v-if="!loading && loadedDone" class="no-more">
                    <div class="no-more-tip">没有更多数据</div>
                </div>
                <div class="foot-line" v-if="loading"> 
                    <img src="../../../css/images/loading.svg" class="loading-icon">正在加载... 
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import utils from '@utils'
import { list, cancelOrder, payOrder, orderDetail } from '../api'
export default {
    name: 'orderList',
    mixins: [ utils.MixinBase ],
    data() {
        return {
            orderStatus: [
                {
                    name: "待付款",
                    status: "UNPAY"
                },
                {
                    name: "待发货",
                    status: "UNSEND",
                },
                {
                    name: "待收货",
                    status: "UNRECEIVED"
                },
                {
                    name: "已完成",
                    status: "FINISHED"
                },
                {
                    name: "已取消",
                    status: "CANCELED"
                },
                {
                    name: "全部",
                    status: "ALL"
                }
            ],
            orderDetail: {},
            pageSize: 10,
            orderList: [],
            currentPage: 0,
            loadedDone: false,

            curStatus: 'UNPAY',
            loading: false,
        }
    },
    mounted() {
        var self = this;
        this.wechatInit().then(()=> {
            this.wechatConfigInit().then(() => {
               this.init(); 
            });
        }, ()=> {
            this.init();
        });
        window.addEventListener("scroll", function() {
            var scrollTopAndOffsetHeight = (document.documentElement.scrollTop||document.body.scrollTop)+document.documentElement.clientHeight;
            var scrollHeight = document.documentElement.scrollHeight;
            if(scrollTopAndOffsetHeight+50>scrollHeight) {
                self.loadData();
            }
        }, false);
    },
    methods: {
        init() {
            this.fetchData();
        },
        fetchData(cb) {
            var param = {
                currentPage: this.currentPage,
                pageSize: this.pageSize
            }
            if(this.curStatus!='ALL') {
                param.status = this.curStatus;
            }
            
            this.loading = true;

            list(param).then((data) => {
                this.loading = false;
                this.currentPage = ++data.currentPage;
                if(data.currentPage >= data.totalPages) {
                    this.loadedDone = true; 
                }
                this.orderList = this.orderList.concat(data.list);
                if(cb) {
                    cb();
                }
            }).catch(err => {
                this.$toast(err && err.info)
                this.loading = false;
            })
        },
        clearData() {
            this.orderList = [];
            this.currentPage = 0;
            this.loadedDone = false;
        },
        computedStartTime(createTime) {
            return new Date(createTime).getTime();
        },
        computedEndTime(createTime) {
            return (new Date(createTime).getTime()+(new Date(createTime).getTime()+2*60*60*1000)-new Date().getTime())
        },
        computedHasEnd(createTime) {
            return (new Date(createTime).getTime()+2*60*60*1000)-new Date().getTime();
        },
        fetchOrderDataByStatus(orderStatusItem) {
            this.curStatus = orderStatusItem.status;
            this.clearData();
            this.$nextTick(() => {
                this.fetchData();
            })
        },
        loadData() {
            if(!this.loadedDone) {
                if(!this.loading) {
                    this.fetchData();
                }
            }
        },
        deleteHandler(orderItem) {
            this.$messagebox({
                title:'',
                message: '确定取消该订单？',
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                showCancelButton: true
            }).then((res)=> {
                if(res === "confirm") {
                    cancelOrder({id: orderItem.id}).then(() => {
                        this.clearData();
                        this.fetchData();
                    })
                }
            })
        },
        payOrder(orderId){
            payOrder({id: orderId}).then((js_json) => {
                this.$indicator.open({
                    spinnerType: 'fading-circle',
                    text: '开始支付'
                });
                wx.chooseWXPay({
                    timestamp: js_json['timeStamp'], // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: js_json['nonceStr'], // 支付签名随机串，不长于 32 位
                    package: js_json['package'], // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                    signType: js_json['signType'], // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: js_json['paySign'], // 支付签名
                    success: (res) => {
                        this.$indicator.close();
                        this.$indicator.open({
                            spinnerType: 'fading-circle',
                            text: '支付成功'
                        });
                        this.clearData();
                        this.fetchData(()=> {
                            this.$indicator.close();
                        });
                    },
                    fail: (failReason) => {
                        alert(JSON.stringify(failReason));
                        this.$indicator.close();
                    },
                    cancel: () => {
                        this.$indicator.close();
                        this.$toast("你取消了支付");
                    }
                })
            });
        },
        openLogisticModal(orderItem) {
            this.$router.push({path: '/order',  query:{ id: orderItem.id } });
        }
    }
}
</script>

<style>
.my_order {
    background: #efefef;
}
.order-finished {
    color: #Fe0000;
}
.my_order .tabs-nav-bar {
    z-index: 2;
    height: 40px;
    line-height: 40px;
    width: 100%;
    position: fixed;
    top: 0;
    display: flex;
    background: #fff;
}
.tab-item-wrap {
    display: flex;
    flex: 1;
    position: relative;
    justify-content: center;
    align-items: center;
    -webkit-tap-highlight-color:transparent;
}
.tab-item {
    position: relative;
    height: 100%;
    padding: 0 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    color: #666;
    -webkit-tap-highlight-color:transparent;
    font-size: 11px;
}
.tab-item.active {
    color: #fe0000;
}
.tab-item.active::after{
    position: absolute;
    width: 100%;
    height: 2px;
    bottom: 1px;
    transform: translateX(-50%);
    left: 50%;
    content: "";
    background: #fe0000;
}
.order-container {
    margin-top: 40px;
}

.order-item-container {
    margin-bottom: 4px;
}

.foot-line {
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    color: #666;
}

.loading-icon {
    width: 20px;
    height: 20px;
    margin-right: 5px;
}
.no-more {
    font-size: 12px;
    display: flex;
    justify-content: center;
    padding-top: 20px;
    padding-bottom: 20px;
    color: #666;
    flex-direction: column;
    align-items: center;
}

.no-more-tip {
    color: #666;
    text-align: center;
}

</style>
